package com.neusoft.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.mapper.CartMapper;
import com.neusoft.mapper.FoodMapper;
import com.neusoft.po.Cart;
import com.neusoft.po.Food;
import com.neusoft.service.CartService;
import com.neusoft.util.Lock;

@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private CartMapper cartMapper;

	@Autowired
	private FoodMapper foodMapper;

	@Override
	@Transactional
	public List<Cart> listCart(Cart cart) {
		List<Cart> carts = cartMapper.listCart(cart);
		
		for(Cart c : carts) {
			int foodId = c.getFoodId();
			Food food = foodMapper.getFoodById(foodId);
			c.setFood(food);
		}
		return carts ;
	}

	@Override
	@Transactional
	public int saveCart(Cart cart) {
		return cartMapper.saveCart(cart);
	}

	@Override
	@Transactional
	public int updateCart(Cart cart) {
		Food food = foodMapper.getFoodById(cart.getFoodId());
		int foodCount = food.getFoodCount() - cart.getQuantity();
		//食物数量多于剩余数量，不执行更新，并返回0
		if (!Lock.FoodCountLock(foodCount)) {
			return 0;
		}
		//购物车中food数量少于1，则删除此条cart记录
		if (!Lock.EmptyLock(cart.getQuantity())) {
			return cartMapper.removeCart(cart);
		}
		return cartMapper.updateCart(cart);
	}

	@Override
	public int removeCart(Cart cart) {
		
		return cartMapper.removeCart(cart);
	}
}
